package org.ants.tinymvc.entity;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Set;

import org.tinygroup.tinydb.Bean;

public abstract class BaseEntity extends IBaseEntity{
	
	public Bean toBean() throws Exception{
		Bean bean = new Bean(this.getClass().getSimpleName());
		Field[] fs = this.getClass().getDeclaredFields();
		for (int i = 0; i < fs.length; i++) {
			Field f = fs[i];
			String fieldName = f.getName();
			String getterMethodName = "get"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
			Method getterMethod = this.getClass().getMethod(getterMethodName);
			bean.setProperty(f.getName(), getterMethod.invoke(this));
		}
		return bean;
	}
	
	public BaseEntity fromBean(Bean bean) throws Exception{
		if(bean == null || bean.size() == 0){
			return null;
		}
		Set<String> keySet = bean.keySet();
		for(String key : keySet){
			if(null == bean.get(key)){
				continue;
			}
			String setterMethodName = "set"+key.substring(0, 1).toUpperCase()+key.substring(1);
			Method setterMethod = this.getClass().getMethod(setterMethodName,  bean.get(key).getClass());
			setterMethod.invoke(this, bean.get(key));
		}
		return this;
	}
}
